import axios from "axios";
import CryptoJS from "crypto-js";
import qs from "qs";

export const getAccessToken = async (
  appId: string,
  appSecret: string
): Promise<any> => {
  let params = getParams(appSecret);
  let res = await axios<any>({
    // url: "https://openapi.lechange.cn/openapi/accessToken",
    url: "/openapi/accessToken",
    method: "post",
    data: {
      system: {
        ver: "1.0",
        appId: appId,
        sign: params.sign,
        time: params.time,
        nonce: params.nonce,
      },
      id: params.id,
      params: {},
    },
  });

  return res.data;
};

export const getKitToken = async (data: {
  token: string;
  deviceId: string;
  channelId: string;
  type: string;
  appSecret: string;
  appId: string;
}): Promise<any> => {
  let params = getParams(data.appSecret);
  let res = await axios<any>({
    // url: "https://openapi.lechange.cn/openapi/getKitToken",
    url: "/openapi/getKitToken",
    method: "post",
    data: {
      system: {
        ver: "1.0",
        appId: data.appId,
        sign: params.sign,
        time: params.time,
        nonce: params.nonce,
      },
      id: params.id,
      params: {
        token: data.token,
        deviceId: data.deviceId,
        channelId: data.channelId,
        type: data.type,
      },
    },
  });

  return res.data;
};

export const queryLocalRecords = async (data: {
  token: string;
  deviceId: string;
  channelId: string;
  appSecret: string;
  appId: string;
  beginTime: string;
  endTime: string
}): Promise<any> => {
  let params = getParams(data.appSecret);
  let res = await axios<any>({
    // url: "https://openapi.lechange.cn/openapi/queryLocalRecords",
    url: "/openapi/queryLocalRecords",
    method: "post",
    data: {
      system: {
        ver: "1.0",
        appId: data.appId,
        sign: params.sign,
        time: params.time,
        nonce: params.nonce,
      },
      id: params.id,
      params: {
        token: data.token,
        deviceId: data.deviceId,
        channelId: data.channelId,
        beginTime: data.beginTime,
        endTime: data.endTime,
        type: "All",
        count: 100,
      },
    },
  });

  return res.data;
};

function getParams(appSecret: string) {
  let target: any = {};
  target.time = Math.round(new Date().getTime() / 1000);
  target.nonce = Math.random().toString(36).substring(2);
  target.sign = getSign(target.time, target.nonce, appSecret);
  target.id = Math.floor(Math.random() * (50 - 1 + 1) + 1); // id仅供参考
  return target;
}

function getSign(timestamp: string, nonce: string, secret: string) {
  let str = `time:${timestamp},nonce:${nonce},appSecret:${secret}`;
  let sign = CryptoJS.MD5(str).toString();
  return sign;
}
